//
//  ComposeViewController.swift
//  Sina
//
//  Created by 王杰 on 15/11/26.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {

    @objc private func selectPicture() {
    
    selectorVC.view.snp_updateConstraints { (make) -> Void in
        make.height.equalTo(224 + 80 + 40)
        
        }
    
    }
    @objc private func close() {
    
    dismissViewControllerAnimated(true, completion: nil)
        
    }
    //发布一条微博
    @objc private func send() {
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token  = UserAccountViewModel().token else {
        
        SVProgressHUD.showErrorWithStatus("你还没有登陆")
            return
        }
        if selectorVC.imageList.count >= 1 {
        
        let imageDate = UIImagePNGRepresentation(selectorVC.imageList[0])
            let parmaters = ["access_token":token,"status":textBoard.text]
            
            NetworkTools.sharedTools.uploadImage(urlString, parmaters: parmaters, imageData: imageDate!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("您还未登陆")
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发布Weibo成功")

            })
        }
//        let urlString = "https://api.weibo.com/2/statuses/update.json"
//        guard let token = UserAccountViewModel().token else {
//        
//            SVProgressHUD.showErrorWithStatus("请登录")
//            
//            return
//        
//        }
//        let parmaters = ["access_token": token,"status": textBoard.text]
//        
//        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
//            if error != nil {
//            
//            SVProgressHUD.showErrorWithStatus(AppErrorTip)
//                return
//            }
//            SVProgressHUD.showSuccessWithStatus("发布成功")
//            self.dismissViewControllerAnimated(true, completion: nil)
//            print(result)
//        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
    }
    
    private func setupUI() {
    
        setNavBar()
        
        setTextView()
        
        setToolBar()
        setSelectorView()
        registerNotification()
    }
    private func setSelectorView() {
    
    addChildViewController(selectorVC)
        view.addSubview(selectorVC.view)
        view.bringSubviewToFront(toolBar)
        
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    
    }
    
        //添加一个通知
    private func registerNotification() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    @objc private func keyboardWillChange(n: NSNotification) {

//        print(n)//次打印的目的是为了获取KEY值 从而有下面的代码
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as!Double
        
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取键盘的高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
            
        }
        UIView.animateWithDuration(duration) { () -> Void in
            
            //强制刷新
            self.view.layoutIfNeeded()
        }

    }
        //设置文本输入框
    private lazy var textBoard: UITextView = {
    
        let vc = UITextView()
        vc.font = UIFont.systemFontOfSize(18)
        vc.backgroundColor = UIColor.grayColor()
        vc.delegate = self
        //回退键盘的处理
        vc.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        vc.alwaysBounceVertical = true
        return vc
 
    }()
    
    private lazy var placeHolderLabel:UILabel = UILabel(title: "分享好事哈", size: 14, color: UIColor.darkGrayColor())
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var selectorVC:PictureSelectorViewController = PictureSelectorViewController()

}

extension ComposeViewController:UITextViewDelegate {

    func textViewDidChangeSelection(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    private func setToolBar() {
    
    view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        
        //设置toolBar
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
        
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            
            let space = UIBarButtonItem(barButtonSystemItem:.FlexibleSpace, target: nil, action: nil)
            
            items.append(space)
        }
        items.removeLast()
        
        toolBar.items = items
    
    }
    
    private func setTextView() {
        
        view.addSubview(textBoard)
        //设置约束
        textBoard.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
            
        }
        textBoard.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textBoard.snp_top).offset(8)
            make.left.equalTo(textBoard.snp_left).offset(5)
        }
        
    }
    private func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false

        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.grayColor())
        let titleName = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.greenColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(titleName)
        
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
            
        }
        
        titleName.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleLabel.snp_bottom).offset(3)
            make.centerX.equalTo(titleLabel.snp_centerX)
        }
    }
    



}



















